import Vue from 'vue'

// 基于Vue.http适配的外观类 简化调用
// 同时使其成为单例
class Fetch {
    /**
     * Constructor
     * 构造函数
     *
     * @param string host 主机地址
     *
     * @return <+Return+>
     */
    constructor(host) {
        if (typeof Fetch.instance === 'object') {
            return Fetch.instance
        }
        this.init(host)
        Fetch.instance = this
        return this
    }

    /**
     * Init
     * 初始化参数配置
     *
     * @param string host 主机地址
     *
     * @return void
     */
    init(host) {
        this.host = typeof host !== 'undefined' ? host : ''

        Vue.http.headers.common['Content-Type'] = 'application/json;charset=UTF-8'
        Vue.http.headers.common['Access-Control-Allow-Origin'] = '*'
        Vue.http.headers.common['Access-Control-Allow-Methods'] = 'GET, OPTIONS'
        Vue.http.headers.common['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    }

    /**
     * Async Get
     * GET方法
     *
     * @param string url 资源的相对地址
     * @param json param 请求的参数
     *
     * @return body|error
     */
    async get(url, param = {}) {
        // console.log(url)
        return Vue.http.get(this.host + url, { params: param }).then(
            response => {
                // console.log('http GET 调用成功')
                return response.body
            },
            () => {
                // console.log(response)
                throw new Error('http GET 调用失败')
            }
        )
    }

    /**
     * Async Post
     * Post方法
     *
     * @param string url 资源相对地址
     * @param json param 请求的参数
     *
     * @return body|error
     */
    async post(url, param = {}) {
        Vue.http.options.emulateJSON = true
        return Vue.http.post(this.host + url, param).then(
            response => {
                // console.log('http POST 调用成功')
                return response.body
            },
            () => {
                // console.log(response)
                throw new Error('http POST 调用失败')
            }
        )
    }
}

export default Fetch
